#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/9/3 15:10
# @Author : 吴敬超
# explain:
import pandas as pd
import threading
import numpy as np
import netCDF4 as nc
import datetime
import csv
import time as ti
import glob
import multiprocessing

print ti.strftime("%Y-%m-%d %H:%M:%S", ti.localtime())

file_path = 'D:\NetCDFfile\ECMWF_mrt_20190101_v1.0_con.nc'
file_obj = nc.Dataset(file_path)

mrt = file_obj.variables['mrt'][:]
lon = file_obj.variables['lon'][:]
lat = file_obj.variables['lat'][:]
time = file_obj.variables['time']

times = nc.num2date(time[:], time.units)
columnsTitles = ['time', 'lat', 'lon', 'mrt']


# class myThread(threading.Thread):  # 继承父类threading.Thread
#     def __init__(self, threadID, name, timets):
#         threading.Thread.__init__(self)
#         self.threadID = threadID
#         self.name = name
#         self.timets = timets
#
#     def run(self):  # 把要执行的代码写到run函数里面 线程在创建后会直接运行run函数
#         print "Starting " + self.name
#
#         filechanger(self.name, self.timets)
#
#         print "Exiting " + self.name


def filechanger(threadName, timets):
    print "thread start Name is" + str(threadName)
    print "%s: %s" % (threadName, ti.ctime(ti.time()))
    print "timets is" + str(timets)

    listtime = []
    listlon = []
    listlat = []
    listmrt = []
    for lata in range(len(lat)):
        for lono in range(len(lon)):
            listtime.append(times[timets].strftime("%Y-%m-%d %H:%M:%S"))
            listlat.append(str(lat[lata]))
            listlon.append(str(lon[lono]))
            # print mrt[timets][lata][lono]
            listmrt.append(str(mrt[timets][lata][lono]))
            # print "thread  Name is" + str(threadName) + '\n'
            # print "lata  Name is" + str(lata) + '\n'
            # print "lono  Name is" + str(lono) + '\n'

    data = {'time': listtime, 'lat': listlat, 'lon': listlon, 'mrt': listmrt}
    df = pd.DataFrame(data)

    csvpath = "D:/fiecsv/ncmrt" + threadName + ".csv"

    print "csvpath is" + csvpath

    df.to_csv(csvpath, index=None, mode='ab', header=False, columns=columnsTitles)
    # print ti.strftime("%Y-%m-%d %H:%M:%S", ti.localtime())
    print "thread end Name is" + str(threadName)

    print "%s: %s" % (threadName, ti.ctime(ti.time()))


def csvhead(csvpath, csvfilehead):
    csvheadpath = csvpath + csvfilehead
    print csvheadpath
    with open(csvheadpath, mode='wb') as ice_file:
        ice_writer = csv.writer(ice_file, dialect='excel')
        ice_writer.writerow(['time', 'lat', 'lon', 'mrt'])
    ice_file.close()


def csvmerger(csvpath, csvtp, csvsoufile):
    globcsvpath = csvpath + csvtp
    csvx_list = glob.glob(globcsvpath)
    sourcepath = csvpath + csvsoufile
    print('总共发现%s个CSV文件' % len(csvx_list))
    # time.sleep(2)
    print('正在处理............')
    for i in csvx_list:
        # print str(csvx_list[i])
        fr = open(i, 'r').read()
        with open(sourcepath, 'a') as f:
            f.write(fr)
        print('写入成功！')
    print('写入完毕！')



# def func(msg):
#     for i in xrange(3):
#         print msg
#         time.sleep(1)



if __name__ == "__main__":
    # print("main")


    filechanger("process-1",0)
